package com.qiteng.apiinterface.controller;


import com.qiteng.apiclientsdk.model.User;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.Instant;

import static com.qiteng.apiclientsdk.utils.SignUtils.generateSign;

/**
 * @author qiteng
 */
@RestController
@RequestMapping("/name")
public class NameController {

    @GetMapping("/")
    public String getNameByGet(String name) {
        return "Get  " + "你的名字是：" + name;
    }

    @PostMapping("/")
    public String getNameByPost(@RequestParam String name) {
        return "POST  " + "你的名字是：" + name;
    }

    @PostMapping("/user")
    public String getNameByUser(@RequestBody User user, HttpServletRequest request) {
        String accessKey = request.getHeader("accessKey");
        String clientSign = request.getHeader("sign");
        String body = request.getHeader("body");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        //根据ak从数据库中查找sk，如果不存在则抛出异常
        if (!"qiteng".equals(accessKey)) {
            throw new RuntimeException("无权限");
        }
        String secretKey = "123456";
        //根据sk和body计算出sign
        String serverSign = generateSign(body, secretKey);
        //比较sign是否相同
        if (!clientSign.equals(serverSign)) {
            throw new RuntimeException("无权限");
        }

        //查看时间是否在5分钟之内
        // 将输入的时间戳转换为 Instant 对象
        long timestampOfLong = Long.parseLong(timestamp);
        Instant inputTime = Instant.ofEpochMilli(timestampOfLong);
        // 获取当前时间的 Instant 对象
        Instant currentTime = Instant.now();
        // 计算时间差
        Duration duration = Duration.between(inputTime, currentTime);
        // 获取时间差的绝对值（以防输入时间在当前时间之后）
        long differenceInMinutes = Math.abs(duration.toMinutes());
        // 检查时间差是否在五分钟之内
        if (differenceInMinutes > 5) {
            throw new RuntimeException("无权限");
        }

        //查看随机数是否在内存中

        return "POST  " + "你的名字是：" + user.getName();
    }
}
